package cn.lyyb2001.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.lyyb2001.admin.mapper.SysUserMapper;
import cn.lyyb2001.admin.pojo.dto.UserAuthDTO;
import cn.lyyb2001.admin.pojo.entity.SysUser;
import cn.lyyb2001.admin.pojo.entity.SysUserRole;
import cn.lyyb2001.admin.service.ISysUserRoleService;
import cn.lyyb2001.admin.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daiyb2
 * @Title: SysUserServiceImpl
 * @Description:
 * @date 2021/10/30 19:19
 **/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    private ISysUserRoleService iSysUserRoleService;
    /**
     * 用户分页列表
     *
     * @param page
     * @param user
     * @return
     */
    @Override
    public IPage<SysUser> list(Page<SysUser> page, SysUser user) {
        List<SysUser> list = baseMapper.list(page, user);
        page.setRecords(list);
        return page;
    }

    @Override
    public UserAuthDTO getByUsername(String username) {
        return baseMapper.getUserInfo(username,null);
    }

    @Override
    public UserAuthDTO getByMobilePhone(String mobilePhone) {
        return baseMapper.getUserInfo(null,mobilePhone);
    }

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean updateUser(SysUser user) {
        List<Long> oldRoleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, user.getId())).stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
        List<Long> newRoleIds = user.getRoleIds();
        //新增角色
        List<Long> addRoleIds = CollectionUtil.subtractToList(newRoleIds,oldRoleIds);
        if (CollectionUtil.isNotEmpty(addRoleIds)) {
            List<SysUserRole> addUserRoleList = new ArrayList<>();
            addRoleIds.forEach(roleId -> {
                addUserRoleList.add(new SysUserRole(user.getId(),roleId));
            });
            iSysUserRoleService.saveBatch(addUserRoleList);
        }
        //移除角色
        List<Long> removeRoleIds = CollectionUtil.subtractToList(oldRoleIds,newRoleIds);
        if (CollectionUtil.isNotEmpty(removeRoleIds)) {
            removeRoleIds.forEach(roleId -> {
                iSysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getId()).eq(SysUserRole::getRoleId, roleId));
            });
        }
        return this.updateById(user);
    }
}
